<template>
  <view class="question-container">
    <v-progress :is-show="isShowProgress">
      <div class="header-wrap">
        <!-- 导航栏 -->
        <hi-navbar fixed transparent="show" :backgroundColor="[237, 240, 243]">
        </hi-navbar>
      </div>

      <template v-if="questionList.length == 0">
        <u-empty text="找不到相关考题" mode="list" margin-top="200"></u-empty>
      </template>

      <div>
        <!-- 试卷列表 -->
        <question-list
          :question-list="questionList"
          :is-show-answer="false"
          can-select
          @collect="onCollect"
          @select="onSelect"
        ></question-list>
      </div>

      <hi-transition :show="timing !== 0">
        <div class="time-wrap" @click.stop="setClose">
          <count-down
            :second="timing"
            :showDay="false"
            backgroundColor="#ECF0F3"
          ></count-down>
        </div>
      </hi-transition>

      <hi-fab :btn-list="btnList" @click="onClickFab"></hi-fab>
    </v-progress>
  </view>
</template>

<script>
import CountDown from "_c/CountDown/CountDown"
import QuestionList from "_c/Question/QuestionList"
import VProgress from "_c/Progress/Progress"
import HiFab from "_c/Fab"

import { mapActions, mapGetters } from "vuex"

let timing = 0
let paperId = null // 试卷id

export default {
  components: {
    CountDown,
    VProgress,
    QuestionList,
    HiFab,
  },

  data() {
    return {
      isShowProgress: false,
      timing: 0,
      btnList: [
        {
          text: "测试模式",
          color: "#ecf0f1",
          imgUrl: "/static/image/time.png",
          imgWidth: 45,
          imgHeight: 45,
          bgColor: "#3498db",
        },
        {
          text: "提交试卷",
          color: "#ecf0f1",
          imgUrl: "/static/image/upload.png",
          imgWidth: 45,
          imgHeight: 45,
          bgColor: "#1ABC9C",
        },
      ],
    }
  },

  async onLoad(option) {
    paperId = option.id
    timing = option.timing // 设置考试时间

    this.page = {
      size: 10,
      current: 0,
      hasNext: false,
    }

    uni.showLoading({ title: "加载题目中..." })
    this.page.hasNext = await this.$store.dispatch("question/getQuestionList", {
      paperId,
      current: this.page.current,
      size: this.page.size,
    })
    uni.hideLoading()
    this.$store.dispatch("question/getQuestionNum", { paperId })
  },

  async onReachBottom(e) {
    if (this.page.hasNext) {
      this.page.current++
      uni.showLoading({ title: "加载题目中..." })
      this.page.hasNext = await this.$store.dispatch(
        "question/getQuestionList",
        {
          paperId,
          current: this.page.current,
          size: this.page.size,
        }
      )
      uni.hideLoading()
    }
  },

  computed: {
    ...mapGetters("question", ["questionList"]),
  },

  methods: {
    /** 收藏问题 */
    onCollect(questionIndex) {
      this.$store.dispatch("question/onCollectQuestion", {
        questionIndex,
        paperId,
      })
    },

    /** 选择选项 */
    onSelect({ id, type, selectIndex }) {
      this.$store.dispatch("question/onSelectOption", {
        id,
        type,
        selectIndex,
      })
    },

    /** 关闭计时 */
    setClose() {
      let self = this
      uni.showModal({
        title: "提示",
        content: "是否停止计时模式",
        success: function (res) {
          if (res.confirm) {
            self.timing = 0
          }
        },
      })
    },

    /** 设置计时 */
    setTiming() {
      if (this.timing === 0) {
        this.timing = +timing == 0 ? 3600 : timing
      } else {
        let self = this
        uni.showModal({
          title: "提示",
          content: "重新计时",
          success: function (res) {
            if (res.confirm) {
              self.timing = timing
            } else if (res.cancel) {
              console.log("用户点击取消")
            }
          },
        })
      }
    },

    /** 提交试卷 */
    async onClickUpload() {
      uni.showModal({
        title: "是否确认提交试卷",
        success: async (res) => {
          if (res.confirm) {
            if (!this.isShowProgress) {
              this.isShowProgress = true
              let wrongQuestionsList = this.questionList
                .filter((item) => {
                  return ["多选", "单选", "判断"].includes(item.type)
                })
                .filter((item) => {
                  if (item.type === "多选") {
                    return item.selectOption.join(",") !== item.right
                  } else {
                    return item.selectOption != item.right
                  }
                })
              wrongQuestionsList = wrongQuestionsList.map((item) => {
                const { content, selectOption, id } = item
                return { content, selectOption, id }
              })
              let QuestionResult = new wx.BaaS.TableObject("paper_result")
              let QuestionPaper = new wx.BaaS.TableObject("paper_paper")

              let MyRecord = QuestionResult.create()
              let questionPaper = QuestionPaper.getWithoutData(paperId)

              MyRecord.set({
                paper: questionPaper,
                wrongQuestions: wrongQuestionsList,
                rightQuestionsNum:
                  this.questionList.length - wrongQuestionsList.length,
                userinfo: this.$store.state.user.userInfo,
                inRank: this.timing !== 0 ? true : false,
              })
              const ResultRes = await MyRecord.save()

              this.saveWrongQuestion(wrongQuestionsList, ResultRes.data.id)

              setTimeout(() => {
                uni.redirectTo({
                  url: `/pages/question/result?resultId=${ResultRes.data.id}&paperId=${paperId}`,
                })
              }, 2500)
            }
          }
        },
      })
    },

    /** 保存错题 */
    async saveWrongQuestion(list, resultId) {
      let QuestionCollect = new wx.BaaS.TableObject("question_error")
      let QuestionPaper = new wx.BaaS.TableObject("question_paper")
      let Question = new wx.BaaS.TableObject("question")
      let Result = new wx.BaaS.TableObject("result")

      let result = Result.getWithoutData(resultId)
      let questionPaper = QuestionPaper.getWithoutData(paperId)

      const records = list.map((item) => {
        return {
          selectOption: String(
            item.selectOption instanceof Array
              ? item.selectOption.join(",")
              : item.selectOption
          ),
          result: result,
          paper: questionPaper,
          question: Question.getWithoutData(item.id),
        }
      })
      const res = await QuestionCollect.createMany(records)
    },

    /** 点击悬浮按钮 */
    onClickFab(e) {
      const { index } = e
      if (index === 1) {
        this.onClickUpload()
      } else if (index === 0) {
        this.setTiming()
      }
    },
  },
}
</script>

<style lang="scss" scope>
.question-container {
  .upload {
    margin-left: 20rpx;
    border-radius: 10px;
    width: 72rpx;
    height: 72rpx;

    background-image: url("../../static/image/upload/upload.png");
    background-repeat: no-repeat;
    background-position: center center;
    background-size: auto 55%;
    // background: #e0e5ec;

    box-shadow: -8px 8px 15px #bec3c9, 8px -8px 15px #fff;
    &:active {
      box-shadow: inset -5px 5px 9px #bec3c9, inset 5px -5px 9px #fff;
    }
  }
  .time-wrap {
    position: fixed;
    right: 220rpx;
    bottom: 64rpx;

    border-radius: 50rpx;
    padding: 24rpx 24rpx;

    background: #ecf0f3;

    box-shadow: 7px 7px 14px #c7c7cb, -7px -7px 14px #fff;
  }
}
</style>
